package com.sunny.framework.core.base.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.springframework.ui.Model;

import com.sunny.framework.core.base.util.Pager;

public abstract class BaseAction<T> implements BaseMethod{


	protected Pager pager = new Pager();
	
	protected Map<String,Object> map = new HashMap<String, Object>();
	
	protected List<Criterion> criterions = new ArrayList<Criterion>();
	
	protected List<Projection> projections = new ArrayList<Projection>();
	
	protected List<Order> orders = new ArrayList<Order>();

	/**
	 * 分页
	 * @param request
	 * @return
	 */
	protected Pager pager(HttpServletRequest request){
	
		map = new HashMap<String, Object>();
		
		criterions = new ArrayList<Criterion>();
		
		projections = new ArrayList<Projection>();
		
		orders = new ArrayList<Order>();
		
		map = new HashMap<String, Object>();
		
		Pager pager = new Pager();
		Integer start = 0;
		Integer limit = 15;
		
		if (request.getParameter("start") != null) {
			start = Integer.parseInt(request.getParameter("start"));
		}
		if(request.getParameter("limit")!=null){
			limit = Integer.parseInt(request.getParameter("limit"));
		}
		
		pager.setPageNum(start);
		pager.setNumPerPage(limit);
		pager.setFirstResults(start);
		pager.setMaxResults(limit);
		
		return pager;
	}
	
	/**
	 * 保存方法 
	 * @param model
	 * @param request
	 * @param response
	 * @param T
	 * @return
	 */
	public Map<String,Object> save(Model model, HttpServletRequest request,
			HttpServletResponse response,T t){
		return map;
	}

	public Map<String, Object> listJson(Model model,
			HttpServletRequest request, HttpServletResponse response) {
		pager = pager(request);
		return map;
	}

	/**
	 * 设置map_data数据
	 * @param obj
	 */
	public void map_data(Object obj){
		map = new HashMap<String, Object>();
		map.put("data", obj);
		map.put("success", true);
	}
	
	/**
	 *设置map_data参数为空的数据 
	 */
	public void map_data(){
		map = new HashMap<String, Object>();
		map.put("success", true);
	}
	
	/**
	 * 返回map,error数据
	 * @param e
	 */
	public void map_eror(Exception e){
		map.put("success", false);
		map.put("errors", e);
	}
	
	/**
	 * string 转成 Long[]
	 * @param str
	 * @return
	 */
	public Long[] stringToLongArray(String str){
		String[] idsS = str.split(",");
		Long[] ids = new Long[idsS.length];
		for(int i=0;i<idsS.length;i++){
			ids[i] = Long.decode(idsS[i]);
		}
		return ids;
	}
	
	/**
	 * map_pager,map 设置
	 * @param list
	 * @param count
	 */
	public void map_pager(List<?> list,Integer count){
		
		map.put("result",list);
		map.put("count", count);
		
	}
	 
}
